//
//  Unilit.swift
//  MazeGame
//
//  Created by Hao Dong on 28/03/2017.
//  Copyright © 2017 Hao Dong. All rights reserved.
//

import Foundation
import SceneKit

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

extension float2 {
    init(_ v: CGPoint) {
        self.init(Float(v.x), Float(v.y))
    }
}

extension SCNTransaction {
    class func animateWithDuration(_ duration: CFTimeInterval = 0.5, timingFunction: CAMediaTimingFunction? = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut), completionBlock: (() -> Void)? = nil, animations: () -> Void) {
        begin()
        self.animationDuration = duration
        self.animationTimingFunction = timingFunction
        animations()
        self.completionBlock = completionBlock
        commit()
    }
}

extension SCNNode {
    func flipUp(completionBlock: (() -> Void)? = nil) {
        SCNTransaction.animateWithDuration(0.5, completionBlock: completionBlock) {
            self.rotation.w += Float.pi
        }
    }
    func flipDown(completionBlock: (() -> Void)? = nil) {
        SCNTransaction.animateWithDuration(0.5, completionBlock: completionBlock) {
            self.rotation.w -= Float.pi
        }
    }
}

extension Array
{
    func random() -> Element
    {
        return self[Int(arc4random_uniform(UInt32(self.count)))]
    }
}

extension SCNScene {
    
    /// 获取当前相机朝向
    ///
    /// - Parameter eulerAngles: 角度
    /// - Returns: 朝向
    func getDirection(with eulerAngles: SCNVector3) -> Direction? {
        let degree = eulerAngles.y.radiansToDegrees
        let xDegree = eulerAngles.x.radiansToDegrees
        if eulerAngles.x.radiansToDegrees <= 90 && eulerAngles.x.radiansToDegrees >= -90 {
            if degree > -45.0 && degree <= 45.0 {
                return Direction.forward //up
            } else if (degree > 45 && degree <= 90) || Int(degree) == -90 {
                return Direction.left
            } else if (degree > -90 && degree <= -45) || Int(degree) == 90 { // -90 ~ -45
                return Direction.right
            }
            return nil
        }
        else if Int(xDegree) == 360 && Int(degree) == -90 {
            return  Direction.left
        }
        else if Int(xDegree) == 360 && Int(degree) == 90 {
            return Direction.right
        }
        else { // == .pi
            if degree >= 45.0 && degree < 90 {
                return Direction.left
            } else if degree >= -45 && degree < 45 {
                return Direction.backward //down
            } else if degree > -90 && degree < -45 {
                return Direction.right
            }
            return nil
        }
    }
}
